import 'package:flutter/material.dart';

class Toast {
  static var _lastMsg;

  static int _lastShowms = 0;

  static get flag => true;

  static OverlayEntry? entry;

  static Future _show(BuildContext context, String msg, int duration) {
    entry = OverlayEntry(
        builder: (BuildContext context) => Positioned(
              //top值，可以改变这个值来改变toast在屏幕中的位置
              top: MediaQuery.of(context).size.height.toDouble() * 0.5,
              child: Container(
                    alignment: Alignment.center,
                    width: MediaQuery.of(context).size.width,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10.0),
                      child: ToastWidget(msg: "test",duration: duration,),
                      // child: _buildToastWidget(context,msg),
                    )
                ),
              ),
    );

    ///往Overlay中插入插入OverlayEntry
    Overlay.of(context)?.insert(entry!);

    ///两秒后，移除Toast
    // Future result = Future.delayed(Duration(milliseconds: duration)).then((value) {
    //   print("移除....");
    //   entry!.remove();
    // });
    // return result;
    return Future(() => 0);
  }

  //toast UI绘制
  static _buildToastWidget(context, String msg) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12.0),
              shape: BoxShape.rectangle,
              color: Colors.black45,
            ),
            child: Padding(
              padding: const EdgeInsets.all(10),
              child: Text(
                  msg,
                  style: const TextStyle(
                      color: Colors.white,
                      decoration: TextDecoration.none,
                      fontSize: 14)
              ),
            )
        )
      ],
    );
  }

  //处理重复多次点击
  static void _handleDuplicateAndShow(
      String message, BuildContext context, int duration) {
    if (_lastMsg == message) {
      //相同信息内容
      int currentms = DateTime.now().millisecondsSinceEpoch;
      int interval = currentms - _lastShowms;
      if (interval > duration) {
        //大于时间间隔 可以显示
        _show(context, message, duration);
        _lastShowms = currentms;
      }
    } else {
      _show(context, message, duration);
      _lastMsg = message;
    }
  }

  /// 提示
  static void showInfo(String message, {required BuildContext context, int duration = 2000}) {
    _handleDuplicateAndShow(message, context, duration);
  }
}


class ToastWidget extends StatefulWidget {
  String msg;

  int duration;

  ToastWidget({super.key,required this.msg,required this.duration});


  @override
  State<ToastWidget> createState() => _ToastState();
}

class _ToastState extends State<ToastWidget> with SingleTickerProviderStateMixin {

  late AnimationController _controller;

  @override
  void initState() {

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    //出发点

    Future((){
      _controller.forward();
      print("播放");

      Future.delayed(Duration(milliseconds: widget.duration - 1)).then((value) async {
        await _controller.reverse();
        Toast.entry!.remove();
      });

    });


    return Center(
      child: FadeTransition(
        opacity: _controller,
        child:Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12.0),
                  shape: BoxShape.rectangle,
                  color: Colors.black45,
                ),
                child: Padding(
                  padding: const EdgeInsets.all(10),
                  child: Text(
                      widget.msg,
                      style: const TextStyle(
                          color: Colors.white,
                          decoration: TextDecoration.none,
                          fontSize: 14)
                  ),
                )
            )
          ],
        ),

      ),
    );
  }
}
